/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import domain.controller.file.CategoriaController;
import domain.controller.file.ImageController;
import domain.model.file.Categoria;
import java.util.Enumeration;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Image;
import util.J2meAppHelper;
import view.components.MObjectList;

/**
 *
 * @author Victorino
 */
public class CategoriaRaizForm implements CommandListener, AppForm {

    private MObjectList list = new MObjectList("Categorias");
    private int SEARCH_INDEX = -1;
    private Command cmdSelect = new Command("Selecionar", Command.ITEM, 1);

    public CategoriaRaizForm() {

        list.addCommand(cmdSelect);
        list.setCommandListener(this);
    }

    public void commandAction(Command arg0, Displayable arg1) {

        if (list.isBackCmdClick(arg0)) {
            J2meAppHelper.getInstance().changeForm(InicialForm.getInicialForm());
            return;
        }

        if (list.getSelectedIndex() == SEARCH_INDEX) {
            J2meAppHelper.getInstance().changeForm(new BuscaForm());
            return;
        }

        Categoria cat = (Categoria) list.getSelectedMObject();
        try {
            if (CategoriaController.getInstance().listSubCategoria(cat).size() > 0) {
                J2meAppHelper.getInstance().changeForm(new CategoriaForm(), cat, true);
            } else {
                J2meAppHelper.getInstance().changeForm(new RegistroForm(), cat, true);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public Displayable getDisplyable() {
        return list;
    }

    public void initialize(Object parameter) {
        try {
            System.gc();
            list.deleteAll();
            SEARCH_INDEX = list.append("Busca rápida", ImageController.getInstance().getBuscaImagem());
            Enumeration en = CategoriaController.getInstance().listCategoriaRaiz().elements();
            while (en.hasMoreElements()) {
                Categoria cat = (Categoria) en.nextElement();
                list.appendMObject(cat, null);
            }
            list.appendBack(InicialForm.getInicialForm());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
